package com.lala.rennigou.service;

import com.alibaba.fastjson.JSONArray;
import com.lala.rennigou.mapper.EasybuyOrderDetailMapper;
import com.lala.rennigou.mapper.EasybuyOrderMapper;
import com.lala.rennigou.mapper.EasybuyProductMapper;
import com.lala.rennigou.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

@Service

public class EasybuyOrderDetailServiceImpl implements EasybuyOrderDetailService{
    @Autowired
    private EasybuyOrderDetailMapper easybuyOrderDetailMapper;
    @Autowired
    private EasybuyOrderMapper easybuyOrderMapper;
    @Autowired
    private EasybuyProductMapper easybuyProductMapper;

    @Override
    public int addOrderDetail(EasybuyOrderDetail easybuyOrderDetail) {
        return easybuyOrderDetailMapper.insert(easybuyOrderDetail);
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int  la(EasybuyOrder easybuyOrder, List<EasybuyProduct> list,int id) {
        try {
            //生成订单
            easybuyOrderMapper.insert(easybuyOrder);
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return -1;
        }
        EasybuyOrder easybuyOrder1 = easybuyOrderMapper.selectUserID(id);
        int i=-1;//-1 增加出错，-2库存不足 1正常
        for (EasybuyProduct e:list){
            EasybuyOrderDetail ea=new EasybuyOrderDetail();
            ea.setOrderid(easybuyOrder1.getId());
            ea.setProductid(Integer.parseInt(e.getId()));
            ea.setQuantity(e.getNum());
            ea.setCost(e.getNum() *e.getPrice());
            if (e.getStock()<e.getNum()){
                try {
                    throw new Exception("抛出异常");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return -2;
                }
            }
            if (addOrderDetail(ea)>0){
                modifyStock(e.getId(),e.getStock()-e.getNum());
                i=1;
            }else {
                i=-1;
            }

        }
        return i;
    }

    @Override
    public EasybuyOrder selectUserID(int userid) {
        return easybuyOrderMapper.selectUserID(userid);
    }

    @Override
    public int modifyStock(String id , int stock) {
        return easybuyProductMapper.modifyStock(id, stock);
    }




}
